package com.bh.controller;

import com.alibaba.fastjson.JSON;
import com.bh.pojo.entry.City;
import com.bh.pojo.entry.Menu;
import com.bh.pojo.entry.Role;
import com.bh.pojo.entry.User;
import com.bh.pojo.vo.UserVO;
import com.bh.service.CityService;
import com.bh.service.RoleService;
import com.bh.service.UserService;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private CityService cityService;
    @Autowired
    private RoleService roleService;

    @RequestMapping("/login")
    public String login(User userC, Model model, HttpSession session){
     User user =  userService.loginUser(userC);
     if (user==null){
         model.addAttribute("loginError","用户名或密码错误");
         return "login";
     }
     session.setAttribute("user",user);
    List<Menu> userMenuList= userService.findMenuByUserId(user.getId());
    session.setAttribute("userMenuList",userMenuList);
      return "index";
    }

    @RequestMapping("/findAll")
    public String findAll(
            @RequestParam(required = false,defaultValue = "1") Integer pageNum,
            @RequestParam(required = false,defaultValue = "1")Integer pageSize,Model model,String  likename){
        PageHelper.startPage(pageNum,pageSize);
        List<UserVO> userList=userService.findAll(likename);
        PageInfo<UserVO> userInfo = new PageInfo<>(userList);
        model.addAttribute("userInfo",userInfo);
        model.addAttribute("likename",likename);
        return "user_list";
    }
    //获取省数据
    @RequestMapping("/city/{pid}")
    @ResponseBody
    public List<City> findCityById(@PathVariable Integer pid){
      List<City> cityList= cityService.findCityById(pid);
        return cityList;
    }
    //获取市数据
    @RequestMapping("/cityName")
    @ResponseBody
    public List<City> findCityByName(@RequestParam String cityName){
        City city= cityService.findCityByName(cityName);
        List<City> cityList = cityService.findCityById(city.getId());
        return cityList;
    }

    //新增用户
    @RequestMapping("/addUser")
    public String addUser(User user, MultipartFile file, String sheng, String shi, String qu, HttpServletRequest request){
        String photo="20240816154458.jpg";
        if (file.getSize()>0){
            String originalFilename = file.getOriginalFilename();
            //图片后缀格式
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //图片名称
            String prefix = UUID.randomUUID().toString().replaceAll("-", "");
            photo=prefix+suffix;
            String realPath = request.getServletContext().getRealPath("/static/img");
            try {
                file.transferTo(new File(realPath,photo));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        user.setPhoto(photo);
        String address = sheng.contains("市") ? sheng + "-" + qu : sheng + "-" + shi + "-" + qu;
        user.setAddress(address);

        System.out.println(user);
        Integer result = userService.addUser(user);
        if (result>0){
            return "redirect:/user/findAll.do";
        }
        return "添加失败";

    }

    //分配角色
    @RequestMapping("toAllocationRole")
    public String toAllocationRole(Integer id,Model model){
        //查询所有角色
        List<Role> roleList = roleService.findAll(null);
        System.out.println(roleList);
        //根据用户id查询所对应的角色
        List<Role> userRoles = roleService.findById(id);

        model.addAttribute("roleList",roleList);
        model.addAttribute("userRoles", JSON.toJSONString(userRoles));
        model.addAttribute("userId",id);
        return "user_allocationRoles";
    }

}
